package cars;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class CarNumber {
	/**统计山西省2013年每个月的汽车销售数量
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		if(args.length!=2){
			System.err.println("user path err!!");
			System.exit(-1);
		}
		@SuppressWarnings("deprecation")
		Job job=new Job(new Configuration(), "carsum");
		job.setJarByClass(CarNumber.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job,new Path(args[1]));
		
		job.setMapperClass(scmap.class);
		job.setReducerClass(screduce.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		job.waitForCompletion(true);
	}
	public static class scmap extends Mapper<LongWritable,Text,Text,IntWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
		String[] lines = value.toString().split(",");
		if(lines.length>2 && lines[1]!=null &&  lines[1]!=""){
			String month=lines[1].trim();
			if (month.length()>0 && !month.equals("")) {
				context.write(new Text(month),new IntWritable(1));
			}
		}
		};
	}
	/*map阶段产生的需要shuffle处理
	 * */
	public static class screduce extends Reducer<Text,IntWritable,Text,IntWritable>{
	
		protected void reduce(Text k2, java.lang.Iterable<IntWritable> values, org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			int sum=0;
			for (IntWritable count : values) {
				sum+=count.get();
			}
			//在最后的结果中,key和value是通过/t来进行分割的
			context.write(new Text(k2.toString()+"月销售数量为："),new IntWritable(sum));
		};
	}
}
